<script setup>
import { ref, watch, computed } from 'vue'
import { useCounterStore } from '@/stores/counter'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import operation from './components/operation.vue'
const router = useRouter()
const route = useRoute()
const counter = useCounterStore()
const isNext = ref(true)
const isPrev = ref(true)
const operationRef = ref(null)
const indexLength = ref(1)
const newQuestion = ref({
    path: '/detail/title/1',
    name: '题目1',
    title: "",
    // 1 单选 2 多选 
    radio: "1",
    // type:1情绪问答题 2问答陈述题
    type: "1",
    list: [],
    // type:1情绪问答题 2问答陈述题 ，type == 2时候 answerRemark 才有效
    answerRemark: "",
},)
function back() {
    router.push('/')
}

function handleNext() {
    const data = newQuestion.value.path.split('/')
    router.push(`/detail/title/${+data[data.length - 1] + 1}`)
}

function handlePrew() {
    const data = newQuestion.value.path.split('/')
    router.push(`/detail/title/${+data[data.length - 1] - 1}`)
}

function showQuestion(value) {
    // 创建新的list数组，避免直接修改原始数据
    const newList = newQuestion.value.list.map(m => {
        // 为每个选项创建新对象
        const newItem = { ...m };
        if (newItem.key == value.key) {
            // 切换当前点击项的状态
            newItem.isBgc = !newItem.isBgc;
        } else if (newQuestion.value.radio == 1) {
            // 单选情况下，其他选项取消选中状态
            newItem.isBgc = false;
        }
        return newItem;
    });

    // 更新list引用，触发视图更新
    newQuestion.value.list = newList;

    // 根据单选或多选更新answer值
    let selectedKeys = [];
    if (newQuestion.value.radio == 1) {
        // 单选：只保留当前选中项或取消选中项
        const currentItem = newList.find(item => item.key == value.key);
        if (currentItem && currentItem.isBgc) {
            selectedKeys = [value.key];
        }
    } else {
        // 多选：收集所有选中项
        newList.forEach(item => {
            if (item.isBgc) {
                selectedKeys.push(item.key);
            }
        });
    }

    // 将选中项的key拼接成字符串
    newQuestion.value.answer = selectedKeys.join(',');

    switch (value.logic) {
        case '1':
            if (progressPercentage.value == 100) {
                return
            }
            handleNext();
            break;
        case '2':
            ElMessage({
                message: '问卷提交成功',
                type: 'success',
            })
            back()
            break;
        case '3':
            const path = '/detail' + value.titleKey
            router.push(path)
            break;
    }
}

// 计算当前题目索引
const currentIndex = computed(() => {
    if (!newQuestion.value.path || !counter.question.length) return 0
    return counter.question.findIndex(item => item.path === newQuestion.value.path) + 1
})

// 计算进度百分比
const progressPercentage = computed(() => {
    if (!counter.question.length) return 0
    return Math.round((currentIndex.value / counter.question.length) * 100)
})

function sumit() {
    console.log(counter.question, '##################')
    back()
    ElMessage({
        message: '问卷提交成功',
        type: 'success',
    })
}

function operationRefShow() {
    operationRef.value.Open()
}

watch(() => route.path, (val) => {
    if (val && counter.question && counter.question.length > 0) {
        // 查找当前题目
        const foundQuestion = counter.question.find(item => item.path == val);
        if (foundQuestion) {
            newQuestion.value = foundQuestion;
            indexLength.value = counter.question;

            // 安全地获取最后一个和第一个题目的路径
            const lastQuestion = counter.question[counter.question.length - 1];
            const firstQuestion = counter.question[0];

            // 检查是否为最后一题
            if (lastQuestion && newQuestion.value.path == lastQuestion.path) {
                isNext.value = false;
            } else {
                isNext.value = true;
            }

            // 检查是否为第一题
            if (firstQuestion && newQuestion.value.path == firstQuestion.path) {
                isPrev.value = false;
            } else {
                isPrev.value = true;
            }
        }
    }
}, {
    immediate: true,
    deep: true
})
</script>

<template>
    <div>
        <el-button type="primary" @click="back">返回</el-button>
        <div class="dialog-content">
            <div class="dialog-body">
                <div class="top">
                    <div class="top-left">
                        <div class="top-left-icon" @click="operationRefShow">
                            <el-icon>
                                <Operation size="20px" class="operation" />
                            </el-icon>
                        </div>
                        <div class="top-left-title">问题进度</div>
                    </div>
                    <div class="top-right">{{ currentIndex }}/{{ counter.question.length }}</div>
                </div>
                <div class="progress">
                    <el-progress :text-inside="true" :stroke-width="26" :percentage="progressPercentage"
                        :show-text="false" />
                </div>
                <div class=" question">
                    <div class="question-tag">
                        <el-tag type="primary" style="margin-right: 4px;" v-if="newQuestion?.type == 1">{{
                            newQuestion?.radio == 1 ? '单选' : '多选' }}</el-tag>
                        <el-tag type="success">{{ newQuestion?.type == 1 ? '情绪问答题' : '问答陈述题' }}</el-tag>
                    </div>
                    <div class="question-title">
                        <div>
                            {{ newQuestion?.title }}
                        </div>
                    </div>
                    <ul class="question-answer" v-if="newQuestion?.type == 1">
                        <li v-for="item in newQuestion?.list" :key="item.key" @click="showQuestion(item)"
                            :style="{ backgroundColor: item.isBgc ? '#409eff' : '#384c7c' }"><span>{{ item.text
                                }}</span>
                            <span v-if="item.remark">
                                <el-popconfirm class="box-item" icon="Opportunity" :icon-color="b8741a"
                                    :title="item.remark" placement="top-end" width="300px">

                                    <template #reference>
                                        <el-icon color="#b8741a">
                                            <InfoFilled />
                                        </el-icon>
                                    </template>
                                    <template #actions="{ confirm, cancel }">
                                        <div style="display: flex;">
                                            <el-button size="small" @click="cancel">我明白了</el-button>
                                        </div>
                                    </template>
                                </el-popconfirm>
                            </span>

                        </li>
                    </ul>
                    <div v-else style="margin-bottom: 20px;">
                        <el-input v-model="newQuestion.answer" placeholder="请输入答案" class="question-answer"
                            type="textarea" />
                    </div>
                </div>
                <div>
                    <el-button type="primary" @click="handlePrew" style="width: 100%;" v-if="isPrev">上一题</el-button>
                </div>
                <div style="margin-top: 12px;">
                    <el-button type="primary" @click="handleNext" style="width: 100%;" v-if="isNext">下一题</el-button>
                </div>
                <div style="margin-top: 12px;">
                    <el-button type="primary" @click="sumit" style="width: 100%;"
                        v-if="progressPercentage == 100">提交</el-button>
                </div>
            </div>
        </div>
        <operation ref="operationRef" />
    </div>
</template>

<style scoped lang="scss">
.dialog-content {
    height: calc(100vh - 200px);

    .dialog-body {
        width: 430px;
        border: 1px solid #ebebeb;
        border-radius: 5px;
        margin: 0 auto;
        height: calc(100vh - 200px);
        padding: 20px;
        background-color: #1c3983;
        color: #fff;
    }
}

.top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 18px;

    .top-left {
        display: flex;
        align-items: center;

        .top-left-icon {
            display: flex;
            align-items: center;
        }

        .top-left-title {
            margin-left: 5px;
        }
    }
}

.progress {
    margin-top: 20px;
    margin-bottom: 20px;
}

.question {
    margin-top: 10px;

    .question-tag {
        margin: 5px 0;
    }

    .question-title {
        margin: 10px 0;
        font-size: 20px;
        margin-bottom: 20px;
    }

    .question-answer {
        font-size: 18px;

        li {
            margin: 20px 0;
            padding: 10px;
            color: #fff;
            border: #384c7c;
            background-color: #384c7c;
            cursor: pointer;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
    }
}

.operation {
    cursor: pointer;
}

.operation:hover {
    color: #409eff;
}

.tooltip-content {
    color: rgba(0, 0, 0, 0.8);
}
</style>
